package com.haoze.nurseapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.enumeration.ConstantEnum;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.DateUtil;
import com.haoze.common.utils.HttpClientUtil;
import com.haoze.common.utils.JSONUtils;
import com.haoze.common.utils.UUIDUtil;
import com.haoze.nurseapp.aop.NurseLogAop;
import com.haoze.nurseapp.dao.BedMapper;
import com.haoze.nurseapp.dao.MealListMapper;
import com.haoze.nurseapp.dao.PatientInHospitalMapper;
import com.haoze.nurseapp.dto.BedDTO;
import com.haoze.nurseapp.model.BedEntity;
import com.haoze.nurseapp.model.PatientInHospitalEntity;
import com.haoze.nurseapp.service.BedService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

@Service
public class BedServiceImpl implements BedService{
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private MealListMapper mealListMapper;
    @Autowired
    PatientInHospitalMapper patientInHospitalMapper;

    @Value("${his.url.circulation}")
    private String circulationUrl;

    private static final Logger log = LoggerFactory.getLogger(NurseLogAop.class);

    public Result queryBedNoStatus(String wardId, String status, Integer page, Integer pageSize){
        String dateTime = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
        PageHelper.startPage(page,pageSize);
        List<Map<String, String>> lists = bedMapper.queryBedNoStatus(wardId, status);
        List<Map<String, String>> inpatNumList = lists.stream().filter(x -> StringUtils.isNotBlank(x.get("inpatNum"))).collect(Collectors.toList());
        List<Map<String, String>> illnessList = new CopyOnWriteArrayList<>();
        if(CollectionUtils.isNotEmpty(inpatNumList)){
            List<String> inpatNums = inpatNumList.stream().map(x -> x.get("inpatNum")).collect(Collectors.toList());
            illnessList = mealListMapper.queryIllnessByInpatNum(inpatNums, dateTime);
        }
        List<Map<String, String>> finalIllnessList = illnessList;
        lists.stream().forEach(x->{
            if(StringUtils.isNotBlank(x.get("inpatNum"))){
                this.getPatientAge(x);
                Map<String, String> filterillness = finalIllnessList.stream().filter(s -> StringUtils.isNotBlank(x.get("inpatNum")) && x.get("inpatNum").equals(s.get("inpatNum"))).findFirst().orElse(null);
                if(filterillness!=null){
                    x.put("disdaseState",filterillness.get("ordersItem"));
                }else {
                    x.put("disdaseState", "普通");//病情
                }
            }else{
                x.put("age","");
                x.put("disdaseState", "");
            }
        });

        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(lists);

        return ResultGenerator.genOkResult(pageInfo);
    }

    private void getPatientAge(Map<String, String> patientInfo) {
        Integer ageYear = patientInfo.get("ageYear") == null ? 0 : Integer.parseInt(patientInfo.get("ageYear"));
        Integer ageMonth = patientInfo.get("ageMonth") == null ? 0 : Integer.parseInt(patientInfo.get("ageMonth"));
        Integer ageDay = patientInfo.get("ageDay") == null ? 0 : Integer.parseInt(patientInfo.get("ageDay"));
        Integer ageHour = patientInfo.get("ageHour") == null ? 0 : Integer.parseInt(patientInfo.get("ageHour"));
        Integer ageMinute = patientInfo.get("ageMinute") == null ? 0 : Integer.parseInt(patientInfo.get("ageMinute"));
        StringBuffer ageStr = new StringBuffer();
        if (ageYear != 0) {
            ageStr.append(ageYear + "岁");
            patientInfo.put("age", ageStr.toString());
            return;
        }
        if (ageMonth != 0) {
            ageStr.append(ageMonth + "月");
        }
        if (ageDay != 0) {
            ageStr.append(ageDay + "天");
        }
        if (ageHour != 0) {
            if (ageDay < 29) {              //28天以上不需要小时
                ageStr.append(ageHour + "小时");
            }
        }
        if (ageMinute != 0) {
            ageStr.append(ageMinute + "分钟");
        }
        if (ageStr.length() == 0) {
            ageStr.append(ageHour + "小时");
            ageStr.append(ageMinute + "分钟");
        }
        patientInfo.put("age", ageStr.toString());
    }

    public Result queryDropDownList(String varCode,String keyWords,Integer page, Integer pageSize,String id){
        PageHelper.startPage(page,pageSize);
        List<Map<String, String>> lists = bedMapper.queryDropDownList(varCode, keyWords,null,null,id);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(lists);
        return ResultGenerator.genOkResult(pageInfo);
    }

    public Result queryBedNoList(String wardId,String keyWords,Integer page, Integer pageSize){
        PageHelper.startPage(page,pageSize);
        List<Map<String, String>> lists = bedMapper.queryBedNoList(wardId, keyWords,null,null);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(lists);
        return ResultGenerator.genOkResult(pageInfo);
    }

    public Result queryPostponeBedNo(String wardId){
        String newBedNo = bedMapper.queryPostponeBedNo(wardId);
        return ResultGenerator.genOkResult(newBedNo);
    }

    @Transactional
    public Result saveBed(BedDTO bedDTO){
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        if(StringUtils.isNotBlank(bedDTO.getBedId())){
            //修改
            BedEntity bedEntity = bedMapper.selectByPrimaryKey(bedDTO.getBedId());
            if(bedEntity==null){
                return ResultGenerator.genFailedResult("无数据不能修改");
            }else{
                String deptCode = patientInHospitalMapper.queryDeptCodeByDeptId(bedDTO.getWardDeptId());
                //判断床号是否被使用
                List<Map<String, String>> list = bedMapper.queryBedNoList(bedDTO.getWardDeptId(), null,bedDTO.getBedNo(),bedDTO.getBedId());
                if(CollectionUtils.isNotEmpty(list)){
                    return ResultGenerator.genFailedResult("床号重复，请重新输入");
                }
                PatientInHospitalEntity patientInHospitalEntity = bedMapper.queryPatientInHospitalInfo(bedEntity.getWardDeptId(), bedEntity.getBedNo());
                if(patientInHospitalEntity!=null && (!bedDTO.getBedNo().equals(bedEntity.getBedNo()) || !bedDTO.getBedStatus().equals(bedEntity.getBedStatus()))){
                    return ResultGenerator.genFailedResult("此床已住人，不能修改床号和状态");
                }
                //对接his
                bedEntity.setBedNo(bedDTO.getBedNo());
                bedEntity.setWardDeptId(bedDTO.getWardDeptId());
                bedEntity.setDeptId(bedDTO.getDeptId());
                //bedEntity.setBedCategory(bedDTO.getBedCategory());
                //bedEntity.setBedGrade(bedDTO.getBedGrade());
                bedEntity.setBedLabel(bedDTO.getBedLabel());
                bedEntity.setWardRoomNo(bedDTO.getWardRoomNo());
                //bedEntity.setBedSex(bedDTO.getBedSex());
                bedEntity.setBedStatus(bedDTO.getBedStatus());
                bedEntity.setGmtModify(new Timestamp(new Date().getTime()));
                List<Map<String, String>> bedSex = bedMapper.queryDropDownList("bed_sex", null,bedDTO.getBedSex(),null,null);
                if(CollectionUtils.isNotEmpty(bedSex)){
                    bedEntity.setBedSex(bedSex.get(0).get("id"));
                }else{
                    bedEntity.setBedSex(null);
                }
                List<Map<String, String>> bedGrade = bedMapper.queryDropDownList("bed_grade", null,bedDTO.getBedGrade(),null,null);
                if(CollectionUtils.isNotEmpty(bedGrade)){
                    bedEntity.setBedGrade(bedGrade.get(0).get("id"));
                }else{
                    bedEntity.setBedGrade(null);
                }
                List<Map<String, String>> bedCategory = bedMapper.queryDropDownList("bed_category", null,bedDTO.getBedCategory(),null,null);
                if(CollectionUtils.isNotEmpty(bedCategory)){
                    bedEntity.setBedCategory(bedCategory.get(0).get("id"));
                }else{
                    bedEntity.setBedCategory(null);
                }
                //对接his
                Map<String, Object> map = new HashMap<>();
                Map<String, Object> requestMap = new HashMap<>();
                Map<String, Object> param = new HashMap<>();
                param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
                param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
                param.put("opr_type", "UPDATE");
                param.put("ward_code", deptCode);
                param.put("bed_no", Integer.parseInt(bedEntity.getBedNo()));
                param.put("bed_label", bedEntity.getBedLabel());
                param.put("room_no", bedEntity.getWardRoomNo());
                param.put("dept_code", patientInHospitalMapper.queryDeptCodeByDeptId(bedDTO.getDeptId()));
                param.put("sex_type", bedDTO.getBedSex());
                param.put("bed_class", bedDTO.getBedGrade());
                param.put("approved_type", bedDTO.getBedCategory());
                param.put("bed_status", bedDTO.getBedStatus());
                param.put("status_flag", "0");
                requestMap.put("request", param);
                map.put("c_request", requestMap);
                map.put("operationID", ConstantEnum.HZQUERY_10019.getKey());
                log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
                System.out.println(JSON.toJSONString(map));
                JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, map);
                log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
                if (null != jsonObject) {
                    Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                    if (resInt < 0) {
                        return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                    }
                }
                bedMapper.updateTmpSysBedDict(deptCode+"-"+bedEntity.getBedNo(),bedEntity.getBedId());
                bedMapper.updateByPrimaryKeySelective(bedEntity);
            }
        }else{
            String deptCode = patientInHospitalMapper.queryDeptCodeByDeptId(bedDTO.getWardDeptId());
            //判断床号是否被使用
            List<Map<String, String>> list = bedMapper.queryBedNoList(bedDTO.getWardDeptId(), null,bedDTO.getBedNo(),null);
            if(CollectionUtils.isNotEmpty(list)){
                return ResultGenerator.genFailedResult("床号重复，请重新输入");
            }

            //新增
            BedEntity bedEntity = new BedEntity();
            BeanUtils.copyProperties(bedDTO,bedEntity);
            List<Map<String, String>> bedSex = bedMapper.queryDropDownList("bed_sex", null,bedDTO.getBedSex(),null,null);
            if(CollectionUtils.isNotEmpty(bedSex)){
                bedEntity.setBedSex(bedSex.get(0).get("id"));
            }else{
                bedEntity.setBedSex(null);
            }
            List<Map<String, String>> bedGrade = bedMapper.queryDropDownList("bed_grade", null,bedDTO.getBedGrade(),null,null);
            if(CollectionUtils.isNotEmpty(bedGrade)){
                bedEntity.setBedGrade(bedGrade.get(0).get("id"));
            }else{
                bedEntity.setBedGrade(null);
            }
            List<Map<String, String>> bedCategory = bedMapper.queryDropDownList("bed_category", null,bedDTO.getBedCategory(),null,null);
            if(CollectionUtils.isNotEmpty(bedCategory)){
                bedEntity.setBedCategory(bedCategory.get(0).get("id"));
            }else{
                bedEntity.setBedCategory(null);
            }
            bedEntity.setBedId(UUIDUtil.randomString());
            bedEntity.initAdd();
            bedEntity.setStopFlag("0");
            bedEntity.setDelFlag("0");
            //对接his
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> requestMap = new HashMap<>();
            Map<String, Object> param = new HashMap<>();
            param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
            param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            param.put("opr_type", "NEW");
            param.put("ward_code", deptCode);
            param.put("bed_no", Integer.parseInt(bedEntity.getBedNo()));
            param.put("bed_label", bedEntity.getBedLabel());
            param.put("room_no", bedEntity.getWardRoomNo());
            param.put("dept_code", patientInHospitalMapper.queryDeptCodeByDeptId(bedDTO.getDeptId()));
            param.put("sex_type", bedDTO.getBedSex());
            param.put("bed_class", bedDTO.getBedGrade());
            param.put("approved_type", bedDTO.getBedCategory());
            param.put("bed_status", bedDTO.getBedStatus());
            param.put("status_flag", "0");
            requestMap.put("request", param);
            map.put("c_request", requestMap);
            map.put("operationID", ConstantEnum.HZQUERY_10019.getKey());
            log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
            System.out.println(JSON.toJSONString(map));
            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, map);
            log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
            if (null != jsonObject) {
                Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                if (resInt < 0) {
                    return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                }
            }
            //新增his和床号的中间表
            bedMapper.saveTmpSysBedDict(deptCode+"-"+bedEntity.getBedNo(),bedEntity.getBedId());
            //新增床号
            bedMapper.insert(bedEntity);


        }
        return ResultGenerator.genOkResult("修改成功");
    }

    public Result queryByBedId(String bedId){
        return ResultGenerator.genOkResult(bedMapper.selectByPrimaryKey(bedId));
    }

    public Result deleteByBedId(String bedId){
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        BedEntity bedEntity = bedMapper.selectByPrimaryKey(bedId);
        if(bedEntity!=null) {
            //根据病区和床号查询该床是否有病人
            PatientInHospitalEntity patientInHospitalEntity = bedMapper.queryPatientInHospitalInfo(bedEntity.getWardDeptId(), bedEntity.getBedNo());
            if(patientInHospitalEntity!=null){
                return ResultGenerator.genFailedResult("此床已住人，不能删除");
            }
            //对接his
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> requestMap = new HashMap<>();
            Map<String, Object> param = new HashMap<>();
            param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
            param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            param.put("opr_type", "DELETE");
            param.put("ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(bedEntity.getWardDeptId()));
            param.put("bed_no", Integer.parseInt(bedEntity.getBedNo()));
            param.put("bed_label", bedEntity.getBedLabel());
            param.put("room_no", bedEntity.getWardRoomNo());
            param.put("dept_code", patientInHospitalMapper.queryDeptCodeByDeptId(bedEntity.getDeptId()));
            List<Map<String, String>> bedSex = bedMapper.queryDropDownList("bed_sex", null, null, bedEntity.getBedSex(),null);
            String bedSexDataValue = "";
            if(CollectionUtils.isNotEmpty(bedSex)){
                bedSexDataValue=bedSex.get(0).get("dataValue");
            }
            List<Map<String, String>> bedGrade = bedMapper.queryDropDownList("bed_grade", null, null, bedEntity.getBedGrade(),null);
            String bedGradeDataValue = "";
            if(CollectionUtils.isNotEmpty(bedGrade)){
                bedGradeDataValue=bedGrade.get(0).get("dataValue");
            }
            List<Map<String, String>> bedCategory = bedMapper.queryDropDownList("bed_category", null, null, bedEntity.getBedGrade(),null);
            String bedCategoryDataValue = "";
            if(CollectionUtils.isNotEmpty(bedCategory)){
                bedCategoryDataValue=bedCategory.get(0).get("dataValue");
            }
            param.put("sex_type", bedSexDataValue);
            param.put("bed_class", bedGradeDataValue);
            param.put("approved_type", bedCategoryDataValue);
            param.put("bed_status", bedEntity.getBedStatus());
            param.put("status_flag", "0");
            requestMap.put("request", param);
            map.put("c_request", requestMap);
            map.put("operationID", ConstantEnum.HZQUERY_10019.getKey());
            log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
            JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, map);
            log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
            if (null != jsonObject) {
                Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                if (resInt < 0) {
                    return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                }
            }
            bedMapper.deleteTmpSysBedDict(bedId);
            bedMapper.deleteByPrimaryKey(bedId);
        }
        return ResultGenerator.genOkResult("删除成功");
    }
}
